import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Spin, Tree } from 'antd';
import SysIcon from '@/pages/common/SysIcon';
import { getMenu4Role, getMenuList4Data, saveMenu4Role } from '@/services/system/menu';

const { TreeNode } = Tree;

// 定义传参
interface RoleMenuParams {
  roleId: string;
}

interface RoleMenuData {
  selectedKeys: string[];
  menuList: System.SysMenu[];
}

/**
 * 角色菜单授权
 *
 * @author zhangby
 * @date 24/9/20 12:08 pm
 */
const RoleMenu: React.FC<RoleMenuParams> = (props, ref) => {
  const [loading, setLoading] = useState(false);
  const [roleMenuData, setRoleMenuData] = useState<RoleMenuData>({
    selectedKeys: [],
    menuList: [],
  });

  // 设值
  const setData = (data: any) => {
    setRoleMenuData({ ...roleMenuData, ...data });
  };

  useImperativeHandle(ref, () => ({
    // changeVal 就是暴露给父组件的方法
    onSubmit: async () => {
      // 提交
      const data = await saveMenu4Role(props.roleId, roleMenuData.selectedKeys.join(','));
      return data;
    },
  }));

  // 初始化
  useEffect(() => {
    try {
      setLoading(true);
      getMenuList4Data().then(async (res) => {
        if (res.code === '000') {
          // 查询选中ID
          const menuIds = await getMenu4Role(props.roleId);
          if (menuIds.code === '000') {
            // console.log(menuIds.result);
            setData({ menuList: res.result, selectedKeys: menuIds.result });
          }
        }
        setLoading(false);
      });
    } catch (e) {
      setLoading(false);
    }
  }, []);

  const renderTreeNodes = (data) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            title={
              <div>
                <SysIcon type={item.icon} style={{ marginRight: 5 }} />
                <span>{item.name}</span>
              </div>
            }
            key={item.id}
            dataRef={item}
          >
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      // eslint-disable-next-line max-len
      return (
        <TreeNode
          title={
            <div>
              <SysIcon type={item.icon} style={{ marginRight: 5 }} />
              <span>{item.name}</span>
            </div>
          }
          key={item.id}
        />
      );
    });
  // @ts-ignore
  return (
    <>
      <h3 style={{ margin: '20px 0' }}>菜单授权</h3>
      <Spin spinning={loading}>
        <Tree
          checkable
          key={loading}
          defaultExpandAll
          checkedKeys={roleMenuData.selectedKeys}
          style={{ marginLeft: 30 }}
          onCheck={(checkedKeys) => setData({ selectedKeys: checkedKeys })}
        >
          {renderTreeNodes(roleMenuData.menuList)}
        </Tree>
      </Spin>
    </>
  );
};

// @ts-ignore
export default forwardRef(RoleMenu);
